import { PureComponent } from 'react';
import { InputItem } from 'antd-mobile';
import MToast from "../../Util/MToast"
import { isNull, handleInputFocusBlur } from "../../../utils/helper"
interface Props {
	value: any,
	onChange: Function,
	setFieldsValue: Function,
	field: string[],
	required?: any,
	readonly?: any,
	disabled?: any,
	place_holder?: string,
	tips?: string,
	max_length?: any,
	label_width?: any,
	hasError: boolean,
	errorMsg: string,
	label_text_align?: any

}
interface State {
	value: any
}
export default class MyInputTel extends PureComponent<Props, State> {
	public state: State = {
		value: this.props.value
	}

	componentWillReceiveProps(nextProps: Props) {
		// Should be a controlled component.
		if ('value' in nextProps) {
			let value = nextProps.value;
			this.setState({
				value
			});
		}
	}

	changeValue = (value) => {
		if (!('value' in this.props)) {
			this.setState({
				value: value
			});
		}
		this.triggerChange(value);
	};

	triggerChange = (changedValue) => {
		const onChange = this.props.onChange;
		if (onChange) {
			onChange(changedValue);
		}
	};

	componentDidMount() {

	}
	onChange = (val) => {
		let { save_to_ls_key } = this.props;
		let value = val;
		const reg = /^(0|[1-9][0-9]*)([0-9\-]*)?$/;
		if ((reg.test(value)) || value === '') {
			console.log(val,11111)
			if (!isNull(save_to_ls_key)) {
				localStorage.setItem(MI_APP_CODE+save_to_ls_key, val);
			}
			this.changeValue(value);
		}
	};
	emitEmpty() {
		const { setFieldsValue, field } = this.props;
		setFieldsValue({
			[field[0]]: null
		})
	}
	render() {
		const { required,required_no_star, readonly, disabled, place_holder, tips, max_length = "20", label_width = 5, hasError, errorMsg, label_text_align = "left", save_to_ls_key,input_style } = this.props;
		let isDisabled = disabled == 1;
		let isReadonly = readonly == 1;
		let { value } = this.state;

		let isRequired = required == 1;
		let requiredClass = "";
		if (isRequired && required_no_star!=1) {
			requiredClass = "required"
		}
		if (!isNull(label_text_align)) {
			requiredClass += " label-text-align-" + label_text_align
		}
		return (
			<div>
				<InputItem
					className={requiredClass}
					onExtraClick={() => {
						MToast.info(tips, 1, null, false)
					}}
					onChange={this.onChange}
					editable={!isReadonly}
					disabled={isDisabled}
					clear
					placeholder={place_holder}
					maxLength={max_length}
					value={value}
					labelNumber={label_width}
					type="tel"
					error={hasError}
					onErrorClick={() => {
						MToast.info(errorMsg, 1, null, false)
					}}
					onFocus={() => {
						handleInputFocusBlur()
					}}
					onBlur={() => {
						handleInputFocusBlur(true);
					}}
					style={{
						...input_style
					}}
				>{this.props.children}</InputItem>
				{
					tips && <p className="tipsStyle">{tips}</p>
				}
			</div>

		)
	}
}
